"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Eye, EyeOff, Loader2, ArrowLeft, AlertCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { PasswordStrength } from "@/components/password-strength"
import { registerUser } from "@/app/actions/auth-actions"

// 辅导员注册表单组件，收集辅导员信息并创建账户
export function CounselorRegistrationForm() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    name: "", // 姓名（合并了firstName和lastName）
    email: "", // 邮箱
    account_id: "", // 教工号 (account_id)
    phoneNumber: "", // 手机号
    academy: "", // 部门
    password: "", // 密码
    confirmPassword: "", // 确认密码
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [error, setError] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  // 处理表单输入变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
  }

  // 表单验证
  const validateForm = () => {
    // 验证密码匹配
    if (formData.password !== formData.confirmPassword) {
      setError("两次输入的密码不一致")
      return false
    }

    // 验证密码长度
    if (formData.password.length < 8) {
      setError("密码长度必须至少为8个字符")
      return false
    }

    if (!/^[A-Za-z0-9]{8,}$/.test(formData.account_id)) {
      setError("教工号格式不正确，必须至少包含8位字母或数字")
      return false
    }

    // 验证手机号（简单验证）
    if (!/^\d{11}$/.test(formData.phoneNumber.replace(/[^0-9]/g, ""))) {
      setError("请输入有效的手机号码")
      return false
    }

    return true
  }

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")

    if (!validateForm()) return

    setIsLoading(true)

    try {
      // 调用注册操作
      const result = await registerUser({
        ...formData,
        role: "counselor",
      })

      if (result.success) {
        router.push("/registration-success")
      } else {
        if (typeof result.message === 'string') {
          setError(result.message);
        } else if (Array.isArray(result.message)) {
          // 处理 FastAPI 错误数组
          const errorMessages = (result.message as Array<{msg?: string}>)
              .map(item => item.msg || '未知错误')
              .join(', ');
          setError(errorMessages);
        } else if (result.message && typeof result.message === 'object') {
          // 处理单个错误对象
          const errorObj = result.message as {msg?: string};
          setError(errorObj.msg || JSON.stringify(result.message));
        } else {
          setError("注册失败，请重试。");
        }
      }
    } catch (err) {
      setError("发生意外错误，请重试。")
    } finally {
      setIsLoading(false)
    }
  }

  // 必填项标记组件
  const RequiredMark = () => <span className="text-red-500 ml-1">*</span>

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Button type="button" variant="ghost" size="sm" className="mb-2 -ml-2" onClick={() => router.push("/register")}>
        <ArrowLeft className="mr-2 h-4 w-4" />
        返回角色选择
      </Button>

      {/* 表单说明 */}
      <div className="flex items-center text-sm text-muted-foreground mb-2">
        <AlertCircle className="h-4 w-4 mr-1" />
        <span>
          带 <RequiredMark /> 的字段为必填项
        </span>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      <div className="space-y-2">
        <Label htmlFor="name">
          姓名
          <RequiredMark />
        </Label>
        <Input
          id="name"
          name="name"
          placeholder="请输入您的姓名"
          value={formData.name}
          onChange={handleChange}
          required
        />
      </div>

      {/* 新增教工号字段 */}
      <div className="space-y-2">
        <Label htmlFor="accountId">
          教工号
          <RequiredMark />
        </Label>
        <Input
            id="account_id"  // 修改为与状态变量名一致
            name="account_id"  // 修改为与状态变量名一致
            placeholder="请输入您的教工号"
            value={formData.account_id}
            onChange={handleChange}
            required
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="email">邮箱</Label>
        <Input
          id="email"
          name="email"
          type="email"
          placeholder="your.name@school.edu"
          value={formData.email}
          onChange={handleChange}
        />
        <p className="text-xs text-muted-foreground">选填，用于接收通知</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="academy">学院</Label>
        <Input
            id="academy"
            name="academy"
            placeholder="例如：信息学院"
            value={formData.academy}
            onChange={handleChange}
        />
        <p className="text-xs text-muted-foreground">选填</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="phoneNumber">
          手机号
          <RequiredMark />
        </Label>
        <Input
          id="phoneNumber"
          name="phoneNumber"
          type="tel"
          placeholder="例如：13812345678"
          value={formData.phoneNumber}
          onChange={handleChange}
          required
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="password">
          密码
          <RequiredMark />
        </Label>
        <div className="relative">
          <Input
            id="password"
            name="password"
            type={showPassword ? "text" : "password"}
            value={formData.password}
            onChange={handleChange}
            required
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
            onClick={() => setShowPassword(!showPassword)}
            tabIndex={-1}
          >
            {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
            <span className="sr-only">{showPassword ? "隐藏密码" : "显示密码"}</span>
          </Button>
        </div>
        <PasswordStrength password={formData.password} />
      </div>

      <div className="space-y-2">
        <Label htmlFor="confirmPassword">
          确认密码
          <RequiredMark />
        </Label>
        <div className="relative">
          <Input
            id="confirmPassword"
            name="confirmPassword"
            type={showConfirmPassword ? "text" : "password"}
            value={formData.confirmPassword}
            onChange={handleChange}
            required
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
            tabIndex={-1}
          >
            {showConfirmPassword ? <EyeOff size={16} /> : <Eye size={16} />}
            <span className="sr-only">{showConfirmPassword ? "隐藏密码" : "显示密码"}</span>
          </Button>
        </div>
      </div>

      <Button type="submit" className="w-full" disabled={isLoading}>
        {isLoading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            注册中...
          </>
        ) : (
          "注册辅导员账号"
        )}
      </Button>

      <div className="text-center text-sm">
        已有账号？{" "}
        <Link href="/login" className="text-primary hover:underline">
          立即登录
        </Link>
      </div>
    </form>
  )
}

